package p2pcdnsim.cdn.example;


import java.util.ArrayList;
import java.util.List;

import p2pcdnsim.cdn.CDN;
import p2pcdnsim.cdn.CDNBuilder;
import p2pcdnsim.cdn.CachingStrategy;
import p2pcdnsim.cdn.OriginServer;
import p2pcdnsim.cdn.PlacementStrategy;
import p2pcdnsim.cdn.RequestRedirector;
import p2pcdnsim.cdn.Surrogate;
import p2pcdnsim.cdn.VideoContent;
import p2pcdnsim.cdn.VoDOriginServer;
import p2pcdnsim.cdn.VoDSurrogate;
import p2pcdnsim.exception.CacheClassInstantiationException;
import p2pcdnsim.exception.ClientDoesNotExistException;
import p2pcdnsim.exception.NodeUnexistentException;
import p2pcdnsim.exception.SurrogateAlreadyInsertedException;
import p2pcdnsim.network.NetworkTopology;




import desmoj.core.simulator.Model;

public class ExampleVodCDNBuilder extends CDNBuilder {
	
	private NetworkTopology topology;
	private PlacementStrategy placementStrategy;
	
	
	public ExampleVodCDNBuilder(NetworkTopology topology, PlacementStrategy placementStrategy) {
		this.topology = topology;
		this.placementStrategy = placementStrategy;
	}
	
	@Override
	public void createNewCDN(Model owner) {
		this.cdn = new CDN(owner,topology);
	}

	@Override
	public void defineClientPlacement() throws NodeUnexistentException {
		this.cdn.placeClient(1, 3);
	}

	@SuppressWarnings("unchecked")
	private CachingStrategy<VideoContent> createCache(String string) throws CacheClassInstantiationException {
		CachingStrategy<VideoContent> cache;
		try {
			Class type = Class.forName("p2pcdnsim.cdn.LRUCaching");
			cache = (CachingStrategy<VideoContent>) type.newInstance();
			
		} catch (Exception e) {
			e.printStackTrace();
			throw new CacheClassInstantiationException(e);
		}
		return cache;
	}

	@Override
	public void createAndPlaceOriginServer() throws NodeUnexistentException {
		OriginServer os = new VoDOriginServer(cdn,"OriginServer");
		
		VideoContent content = new VideoContent(0,1000000,300000);
		os.addContent(content);
		
		cdn.placeOriginServer(os,topology.getNode(4));
	}

	@Override
	public void createAndPlaceRequestRedirector() throws NodeUnexistentException {
		RequestRedirector redirector = new RequestRedirector(cdn,"RequestRedirector");
		cdn.placeRequestRedirector(redirector,topology.getNode(1));
	}

	@Override
	public void createAndPlaceSurrogates() throws CacheClassInstantiationException, SurrogateAlreadyInsertedException {
		List<Surrogate> surrogates = new ArrayList<Surrogate>();
		CachingStrategy<VideoContent> cache = createCache("p2pcdnsim.cdn.LRUCaching");
		cache.setCacheSize(5000000);
		Surrogate surrogate = new VoDSurrogate(cdn.getModel(), "Surrogate"+1, cdn, cache);
		surrogates.add(surrogate);
		
		
		placementStrategy.placeSurrogates(surrogates,cdn);
	}

	@Override
	public void insertClientRequests() throws ClientDoesNotExistException {
		this.cdn.addClientRequest(1,1,0);
		this.cdn.addClientRequest(50,1,0);
	}
	
	
}
